#!/bin/sh

# 基础设定
set -e # 遇到非 0 命令返回就退出

# 基础路径计算
SCRIPT_NAME=$(basename $0) # 脚本名称
SCRIPT_HOME=$(dirname $0) # 脚本根路径
APP_HOME=$(cd $SCRIPT_HOME;pwd) # 应用根路径

# 函数定义
# 输出信息
print()
{
    echo "info: $1"
}
# 输出错误信息
printError()
{
    echo "error: $1"
    exit 1
}
# 输出常规用法说明
printUsage()
{
    echo ""
    echo "Usage:$SCRIPT_NAME [parameters]"
    echo "Required parameter is one of:"
    echo "   start     start $SCRIPT_NAME"
    echo "   stop      stop  $SCRIPT_NAME"
    echo "   status    show status of $SCRIPT_NAME"
    echo ""
    exit 1
}
# 获取 java 命令路径
getJavaHome()
{
    if [ "$JAVA_HOME" != "" ]; then
        JAVA_HOME=$JAVA_HOME
    else
        JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:bin/java::")
    fi
    if [ "$JAVA_HOME" = "" ]; then
        printError "JAVA_HOME is not set"
    fi
}
# 获取可执行 Jar
getExecutableJar()
{
    for jar in $APP_HOME/*.jar
    do 
        EXECUTABLE_JAR=${jar}
    done
}
# 设定 Java 运行时配置
setJavaRuntimeConfig()
{
    # 获取 java 路径
    getJavaHome

    # 获取可执行 Jar
    getExecutableJar
}
# 启动
start(){
    # 设定 Java 运行时配置
    setJavaRuntimeConfig

    # 计算应用是否处于运行状态
    RUNNING=$(ps -ef|grep $EXECUTABLE_JAR|grep -v grep|awk '{print $2}')
    if [ -n "$RUNNING" ]; then
        # 正在运行
        print "$EXECUTABLE_JAR is running"
    else
        # 未运行，立即运行
          print "$JAVA_HOME/bin/java $JAVA_OPTS $JMX_OPTS $AGENT_OPTS -jar $CATALINA_OPTS $EXECUTABLE_JAR"
          $JAVA_HOME/bin/java $JAVA_OPTS $JMX_OPTS $AGENT_OPTS -jar $CATALINA_OPTS $EXECUTABLE_JAR
        # 暂停 2 秒等待启动
        sleep 2s
        # 日志输出
        if [ $? -eq 0 ]; then
            print "$EXECUTABLE_JAR start success"
        else
            printError "$EXECUTABLE_JAR start failed"
        fi
    fi
}
# 状态查询
status(){
    # 设定 Java 运行时配置
    setJavaRuntimeConfig

    # 获取应用进程 ID
    PROCESS_ID='pgrep -f "$EXECUTABLE_JAR"'
    if [ "$PROCESS_ID" ]; then
        print "$EXECUTABLE_JAR is running as process $PROCESS_ID"
    else
        print "$EXECUTABLE_JAR is not running."
    fi
}
# 停止
stop(){
    # 设定 Java 运行时配置
    setJavaRuntimeConfig

    # 停止
    print "stopping $EXECUTABLE_JAR..."
    pkill -f $EXECUTABLE_JAR
    print "$EXECUTABLE_JAR is stopped"
}

# 脚本逻辑
# 基础校验
# 校验是否携带参数
if [ $# = 0 ];then
    printUsage
fi
# 命令执行
while true; do
    case "$1" in
    start) start; break;;
    status) status; break;;
    stop) stop; break;;
    *) printUsage;
    esac
done
# 脚本返回
exit $?;
